package com.bank.backend.boot.server.advice;

import com.bank.backend.boot.base.model.response.BaseResponse;
import com.bank.backend.boot.base.model.response.CommonResponse;
import com.bank.backend.boot.server.annotation.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 封装返回结果
 *
 * @author jiaowei
 * @since 2025/3/23 19:24
 */
@RestControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return Objects.nonNull(returnType.getMethodAnnotation(ResponseResult.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        // 如果是 Void 类型，则直接返回 BaseResponse
        if (returnType.getParameterType() == Void.class) {
            return BaseResponse.instance();
        }
        // 否则，返回 CommonResponse
        return CommonResponse.instance().setData(body);
    }
}
